<template>
  <div class="gantt-container">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <el-button type="success" class="add-btn" @click="addTicketLedger">
        <el-icon>
          <Plus />
        </el-icon>
        新建生产订单
      </el-button>
      <el-input v-model="TicketLedgerData.tickeNumber" placeholder="请输入订单编号" class="search-input" clearable>
        <template #prefix>
          <span class="input-label">订单编号</span>
        </template>
      </el-input>
      <el-select v-model="TicketLedgerData.ordersState" placeholder="请选择订单状态" class="search-select" clearable>
        <template #prefix>
          <span class="input-label">订单状态</span>
        </template>
        <el-option label="创建" :value="0" />
        <el-option label="进行中" :value="1" />
        <el-option label="已完成" :value="2" />
      </el-select>
      <el-button type="primary" @click="getTableData">
        <el-icon>
          <Search />
        </el-icon>
        搜索
      </el-button>
    </div>

    <!-- 甘特图主体 -->
    <div class="gantt-wrapper">

      <!-- 左侧产品信息（分组+对齐） -->
      <div class="product-info align-mode">
        <div class="header-placeholder" style="height: 95px; background: #f5f7fa;"></div>
        <template v-for="order in tableData" :key="order.tickeNumber">
          <div class="product-group-title align">产线:{{ order.line }}</div>
          <div class="order-info">
            <span class="order-id">订单编号:{{ order.tickeNumber }}</span>
            <span class="order-stats">计划:{{ order.plan }} 完成:{{ order.produce }} 次品:{{ order.defectiveProduct }}</span>
          </div>
        </template>
      </div>
      <!-- 右侧甘特图（分组+对齐） -->
      <div class="gantt-chart" ref="ganttChartRef">
        <!-- 时间轴头部（可横向滚动，随内容区同步） -->
        <div class="timeline-header-wrapper" ref="timelineHeaderRef"
          style="overflow-x: auto; overflow-y: hidden; background: #f5f7fa;">
          <div class="timeline-header" :style="`min-width: ${dateRange.length * 40}px;`">
            <div class="month-row">
              <div v-for="(group, index) in monthGroups" :key="index" class="month-cell"
                :style="{ width: group.width }">
                {{ group.month }}
              </div>
            </div>
            <div class="date-row">
              <div v-for="date in dateRange" :key="date.date + date.month" class="date-cell"
                :class="{ 'weekend': date.weekday === '六' || date.weekday === '日' }">
                <div class="date-number">{{ date.date }}</div>
                <div class="weekday">{{ date.weekday }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 甘特图内容区（正方形格子，滚动条正常） -->
        <div class="gantt-content" ref="ganttContentRef" @scroll="handleContentScroll">
          <div class="tasks-container align-mode" :style="`min-width: ${dateRange.length * 40}px;`">
            <template v-for="order in tableData" :key="order.tickeNumber">
              <div class="gantt-row align">
                <div class="grid-row">
                  <div v-for="date in dateRange" :key="date.date + date.month" class="grid-cell"></div>
                </div>
                <div class="progress-bar align" 
                  :style="getProgressBarStyle(order)"
                  :data-status="getOrderStatus(order)"
                  @click="updateTicketLedger(order)">
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    
    <el-dialog v-model="dialogFormVisible1" title="添加" width="1000">
      <el-form ref="ruleFormRef" style="max-width: 600px;" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="订单号" prop="tickeNumber">
          <el-input v-model="ruleForm.tickeNumber" disabled/>
        </el-form-item>
        <el-form-item label="工艺路线" prop="line">
          <el-select v-model="ruleForm.line">
            <el-option v-for="item in operationaldata" :label="item.routing" :value="item.routing" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划数量" prop="plan">
          <el-input v-model="ruleForm.plan" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="stateTime">
          <el-input v-model="ruleForm.stateTime" type="date" />
        </el-form-item>
        <el-form-item label="计划结束时间" prop="endTime">
          <el-input v-model="ruleForm.endTime" type="date" />
        </el-form-item>
        <el-form-item label="BOM" prop="bomcode">
          <el-select v-model="ruleForm.bomcode" >
            <el-option v-for="item in bomdata" :label="item.materialName" :value="item.materialName" />
          </el-select>
        </el-form-item>
        <el-form-item label="二维码" prop="qrCode">
          <el-input v-model="ruleForm.qrCode" disabled/>
        </el-form-item>
        <el-form-item label="已经生产" prop="produce">
          <el-input v-model="ruleForm.produce" />
        </el-form-item>
        <el-form-item label="不合格品" prop="defectiveProduct">
          <el-input v-model="ruleForm.defectiveProduct" />
        </el-form-item>
        <el-form-item label="一次通过率" prop="firstPassRate">
          <el-input v-model="ruleForm.firstPassRate" />
        </el-form-item>
        <el-form-item label="订单完成率" prop="orderFulfillmentRate">
          <el-input v-model="ruleForm.orderFulfillmentRate" />
        </el-form-item>
        <el-form-item label="状态" prop="ordersState">
          <el-select v-model="ruleForm.ordersState">
            <el-option label="创建" :value="0" />
            <el-option label="进行中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="ruleForm.createTime" type="date" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm1(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="dialogFormVisible1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible2" title="修改" width="1000">
      <el-form ref="ruleFormRef" style="max-width: 600px;" :model="ruleForm" :rules="rules" label-width="auto">
        <el-form-item label="订单号" prop="tickeNumber">
          <el-input v-model="ruleForm.tickeNumber" disabled/>
        </el-form-item>
        <el-form-item label="工艺路线" prop="line">
          <el-select v-model="ruleForm.line">
            <el-option v-for="item in operationaldata" :label="item.routing" :value="item.routing" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划数量" prop="plan">
          <el-input v-model="ruleForm.plan" />
        </el-form-item>
        <el-form-item label="计划开始时间" prop="stateTime">
          <el-input v-model="ruleForm.stateTime" type="date" />
        </el-form-item>
        <el-form-item label="计划结束时间" prop="endTime">
          <el-input v-model="ruleForm.endTime" type="date" />
        </el-form-item>
        <el-form-item label="BOM" prop="bomcode">
          <el-select v-model="ruleForm.bomcode" >
            <el-option v-for="item in bomdata" :label="item.materialName" :value="item.materialName" />
          </el-select>
        </el-form-item>
        <el-form-item label="二维码" prop="qrCode">
          <el-input v-model="ruleForm.qrCode" disabled/>
        </el-form-item>
        <el-form-item label="已经生产" prop="produce">
          <el-input v-model="ruleForm.produce" />
        </el-form-item>
        <el-form-item label="不合格品" prop="defectiveProduct">
          <el-input v-model="ruleForm.defectiveProduct" />
        </el-form-item>
        <el-form-item label="一次通过率" prop="firstPassRate">
          <el-input v-model="ruleForm.firstPassRate" />
        </el-form-item>
        <el-form-item label="订单完成率" prop="orderFulfillmentRate">
          <el-input v-model="ruleForm.orderFulfillmentRate" />
        </el-form-item>
        <el-form-item label="状态" prop="ordersState">
          <el-select v-model="ruleForm.ordersState">
            <el-option label="创建" value="0" />
            <el-option label="进行中" value="1" />
            <el-option label="已完成" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="ruleForm.createTime" type="date" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm2(ruleFormRef)">
            确定
          </el-button>
          <el-button @click="dialogFormVisible2 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>



    <!-- 底部控制栏始终显示 -->
    <div class="control-bar custom-bar">
      <div class="bar-inner">
        <el-button-group class="page-control">
          <el-button>
            <el-icon>
              <ArrowLeft />
            </el-icon>
          </el-button>
          <el-button>1 / 1</el-button>
          <el-button>
            <el-icon>
              <ArrowRight />
            </el-icon>
          </el-button>
        </el-button-group>
        <el-button circle>
          <el-icon>
            <RefreshRight />
          </el-icon>
        </el-button>
        <el-button circle>
          <el-icon>
            <Timer />
          </el-icon>
        </el-button>
        <el-slider v-model="scrollPosition" :min="0" :max="100" :format-tooltip="(val: number) => `${val}%`"
          @input="handleScroll" style="width: 180px; margin: 0 12px; vertical-align: middle;" />
        <el-button-group>
          <el-button>
            <el-icon>
              <ZoomIn />
            </el-icon>
          </el-button>
          <el-button>
            <el-icon>
              <ZoomOut />
            </el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ref, computed, onMounted, nextTick, reactive, h } from 'vue'
import {
  Plus,
  Search,
  ArrowLeft,
  ArrowRight,
  RefreshRight,
  Timer,
  ZoomIn,
  ZoomOut
} from '@element-plus/icons-vue'
import http from '@/api/http'

onMounted(() => {
  getTableData()
  getbomdata();
})

const TicketLedgerData = reactive({
  tickeNumber: '',
  ordersState: ''
})

// 定义接口
interface TicketLedger {
  tickeId: number
  tickeNumber: string
  line: string
  plan: number
  stateTime: string
  endTime: string
  state: string
  produce: number
  defectiveProduct: number
  ordersState: number
  bomcode: string
  qrCode: string
  firstPassRate: string
  orderFulfillmentRate: string
  createTime: string
  remark: string
}

// 定义日期项接口
interface DateItem {
  date: number;
  weekday: string;
  month: number;
  year: number;
  fullDate: Date;
}

// 定义订单信息接口
interface OrderInfo {
  id: string
  displayText: string
  planQuantity: number
  completedQuantity: number
  defectQuantity: number
  startDate: string
  endDate: string
  status: 'completed' | 'processing' | 'created'
  line: string
}

// 定义扁平行数据接口
interface FlatRow {
  isGroup: boolean
  key: string
  line?: string
  order?: OrderInfo
}

// 搜索表单
const searchForm = ref({
  orderNo: '',
  status: ''
})

// 工单数据
const tableData = ref<any>([])

// 获取工单列表信息
const getTableData = () => {
  http.get('/api/ProductionManagement/GetTicketLedgerList?tickeNumber=' + TicketLedgerData.tickeNumber + '&ordersState=' + TicketLedgerData.ordersState).then(res => {
    if (res.data && Array.isArray(res.data)) {
      tableData.value = res.data
    }
  })
}
//#region 新增甘特图
const dialogFormVisible1 = ref(false)
const addTicketLedger = () => {
  ruleForm.tickeNumber = ''
  ruleForm.line = ''
  ruleForm.plan = ''
  ruleForm.stateTime = ''
  ruleForm.endTime = ''
  ruleForm.bomcode = ''
  ruleForm.qrCode = ''
  ruleForm.produce = ''
  ruleForm.defectiveProduct = ''
  ruleForm.firstPassRate = ''
  ruleForm.orderFulfillmentRate = ''
  ruleForm.remark = ''
  ruleForm.ordersState = ''
  ruleForm.createTime = ''
  getproductSequence()
  getCodedata()
  getoperationaldata()
  dialogFormVisible1.value = true
}

const ruleFormRef = ref()
const ruleForm = reactive({
  "tickeId": 0,
  "tickeNumber": "",
  "line": "",
  "plan": "",
  "stateTime": "",
  "endTime": "",
  "bomcode": "",
  "qrCode": "",
  "produce": "",
  "defectiveProduct": "",
  "firstPassRate": "",
  "orderFulfillmentRate": "",
  "remark": "",
  "ordersState": "",
  "createTime": ""
})

const getproductSequence = () => {
    http.get('api/Bom/GetBomCode').then(res => {
        ruleForm.tickeNumber = res.toString();

    })
}
const getCodedata = () => {
    http.get('/api/TeamManagement/GetCode').then(res => {
        console.log(res)
        ruleForm.qrCode = res.toString()
    })
}

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  tickeNumber: [
    { required: true, message: '订单编号不能为空', trigger: 'blur' }
  ],
  line: [
    {
      required: true,
      message: '工艺路线不能为空',
      trigger: 'change',
    },
  ],
  plan: [
    {
      required: true,
      message: '计划数量不能为空',
      trigger: 'change',
    },
  ],
  stateTime: [
    {
      type: 'date',
      required: true,
      message: '开始时间不能为空',
      trigger: 'change',
    },
  ],
  endTime: [
    {
      type: 'date',
      required: true,
      message: '结束时间不能为空',
      trigger: 'change',
    },
  ],
  bomcode: [
    {
      required: true,
      message: 'BOM编码不能为空',
      trigger: 'change',
    },
  ],
  qrCode: [
    {
      required: true,
      message: '二维码不能为空',
      trigger: 'change',
    },
  ],
  produce: [
    {
      required: true,
      message: '已经生产产品不能为空',
      trigger: 'blur'
    },
  ],
  defectiveProduct: [
    {
      required: true,
      message: '不合格产品不能为空',
      trigger: 'blur'
    },
  ],
  firstPassRate: [
    {
      required: true,
      message: '一次通过率品不能为空',
      trigger: 'blur'
    },
  ],
  orderFulfillmentRate: [
    {
      required: true,
      message: '订单完成率不能为空',
      trigger: 'blur'
    },
  ],
  remark: [
    {
      required: true,
      message: '备注不能为空',
      trigger: 'blur'
    },
  ],
  ordersState: [
    {
      required: true,
      message: '订单状态不能为空',
      trigger: 'blur'
    },
  ],
  createTime: [
    {
      required: true,
      message: '创建时间不能为空',
      trigger: 'blur'
    },
  ],
})

const submitForm1 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!',ruleForm)
      http.post("/api/ProductionManagement/AddTicketLedger",ruleForm).then(res=>{
        console.log(ruleForm)
        console.log("新增成功");
        dialogFormVisible1.value = false
        getTableData();
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//#endregion

//#region 修改甘特图
const dialogFormVisible2 = ref(false)
const updateTicketLedger = (order: TicketLedger) => {
  // 从tableData中查找对应的订单数据
  const orderData = tableData.value.find((item: TicketLedger) => item.tickeNumber === order.tickeNumber)
  if (orderData) {
    console.log('原始数据:', orderData)
    // 将数据填充到表单中
    ruleForm.tickeId = orderData.tickeId
    ruleForm.tickeNumber = orderData.tickeNumber
    ruleForm.line = orderData.line
    ruleForm.plan = orderData.plan
    
    // 处理日期格式
    const formatDate = (dateStr: string) => {
      if (!dateStr) return ''
      // 尝试处理不同的日期格式
      const date = new Date(dateStr)
      if (isNaN(date.getTime())) return dateStr
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    ruleForm.stateTime = formatDate(orderData.stateTime)
    ruleForm.endTime = formatDate(orderData.endTime)
    console.log('处理后的日期:', ruleForm.stateTime, ruleForm.endTime)
    
    ruleForm.bomcode = orderData.bomcode
    ruleForm.qrCode = orderData.qrCode
    ruleForm.produce = orderData.produce
    ruleForm.defectiveProduct = orderData.defectiveProduct
    ruleForm.firstPassRate = orderData.firstPassRate
    ruleForm.orderFulfillmentRate = orderData.orderFulfillmentRate
    ruleForm.ordersState = String(orderData.ordersState)
    ruleForm.createTime = formatDate(orderData.createTime)
    ruleForm.remark = orderData.remark
    
    dialogFormVisible2.value = true
  }
}

const submitForm2 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      http.post("/api/ProductionManagement/UpdateTicketLedger", ruleForm).then(res => {
        console.log("修改成功");
        dialogFormVisible2.value = false
        getTableData();
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//#endregion


//#region 查询BOM数据
const bomdata = ref<any>([])
const getbomdata = () => {
  http.get("/api/ProductionManagement/GetBOM").then(res => {
    bomdata.value = res.data
  })
}

//#endregion

//#region 查询工艺路线数据
const operationaldata = ref<any>([])
const getoperationaldata = () => {
  http.get("/api/ProductionManagement/GetOperational").then(res => {
    operationaldata.value = res.data
  })
}

//#endregion


//#region 查询订单数据
const orderdata = ref([])
const getorderdata = () => {
  http.get("/api/ProductionManagement/GetOrder").then(res => {
    orderdata.value = res.data
  })
}

//#endregion




// 滚动控制
const scrollPosition = ref(0)
const ganttContentRef = ref<HTMLElement | null>(null)
const ganttChartRef = ref<HTMLElement | null>(null)
const timelineHeaderRef = ref<HTMLElement | null>(null)

// 悬停状态
const hoveredOrder = ref<string | null>(null)

// 生产订单数据
const productionOrders = ref([
  {
    id: 'DD202407220001',
    productName: '产线:磁阻传感器',
    planQuantity: 3000,
    completedQuantity: 600,
    defectQuantity: 5,
    startDate: '2024-07-24',
    endDate: '2024-07-28',
    status: 'processing'
  },
  {
    id: 'DD202408090001',
    productName: '产线:测速传感器',
    planQuantity: 1000,
    completedQuantity: 450,
    defectQuantity: 2,
    startDate: '2024-08-09',
    endDate: '2024-08-12',
    status: 'created'
  },
  {
    id: 'DD202408090002',
    productName: '产线:压力传感器',
    planQuantity: 1000,
    completedQuantity: 640,
    defectQuantity: 6,
    startDate: '2024-08-10',
    endDate: '2024-08-11',
    status: 'completed'
  },
  {
    id: '20250527',
    productName: '产线:测速传感器',
    planQuantity: 1000,
    completedQuantity: 1000,
    defectQuantity: 4,
    startDate: '2024-08-15',
    endDate: '2024-08-18',
    status: 'completed'
  }
])

// 生成和左侧一模一样的扁平行数据
const flatRows = computed(() => {
  const rows: FlatRow[] = []
  
  // 遍历 tableData，保持与左侧完全相同的顺序
  tableData.value.forEach((order: TicketLedger) => {
    // 将订单数据转换为进度条所需的格式
    const orderInfo: OrderInfo = {
      id: order.tickeNumber,
      displayText: `计划${order.plan} 完工${order.produce} 次品${order.defectiveProduct}`,
      planQuantity: order.plan,
      completedQuantity: order.produce,
      defectQuantity: order.defectiveProduct,
      startDate: order.stateTime,
      endDate: order.endTime,
      status: order.ordersState === 2 ? 'completed' :
             order.ordersState === 1 ? 'processing' : 'created',
      line: order.line
    }
    
    // 添加订单行
    rows.push({
      isGroup: false,
      key: orderInfo.id,
      order: orderInfo
    })
  })

  return rows
})

// 日期范围生成
const dateRange = computed(() => {
  const dates: DateItem[] = []
  let start, end;

  // 根据数据确定日期范围
  if (tableData.value && tableData.value.length > 0) {
    // 获取所有开始和结束时间
    const allDates = tableData.value.map((order: TicketLedger) => ({
      start: new Date(order.stateTime),
      end: new Date(order.endTime)
    }));

    // 找出最早和最晚的日期
    start = new Date(Math.min(...allDates.map((d: { start: Date }) => d.start.getTime())));
    end = new Date(Math.max(...allDates.map((d: { end: Date }) => d.end.getTime())));

    // 扩展日期范围，前后各显示3天
    start.setDate(start.getDate() - 3);
    end.setDate(end.getDate() + 3);
  } else {
    // 如果没有数据，使用当前月份作为默认范围
    start = new Date();
    start.setDate(1);
    end = new Date();
    end.setMonth(end.getMonth() + 1, 0);
  }

  const weekdays = ['日', '一', '二', '三', '四', '五', '六']
  const dates_array: Date[] = []

  // 生成日期范围
  for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
    dates_array.push(new Date(d))
  }

  // 按月份分组
  const monthGroups = dates_array.reduce<Record<string, Date[]>>((groups, date) => {
    const monthKey = `${date.getFullYear()}-${date.getMonth() + 1}`
    if (!groups[monthKey]) {
      groups[monthKey] = []
    }
    groups[monthKey].push(date)
    return groups
  }, {})

  // 生成最终日期数据
  Object.entries(monthGroups).forEach(([monthKey, monthDates]) => {
    monthDates.forEach((d: Date) => {
      dates.push({
        date: d.getDate(),
        weekday: weekdays[d.getDay()],
        month: d.getMonth() + 1,
        year: d.getFullYear(),
        fullDate: new Date(d)
      })
    })
  })

  return dates
})

// 月份分组计算
const monthGroups = computed(() => {
  if (!dateRange.value.length) return []

  const groups: { month: string; width: string }[] = []
  let currentMonth: string | null = null
  let currentWidth = 0

  dateRange.value.forEach((date) => {
    const monthKey = `${date.year}年${date.month}月`
    if (monthKey !== currentMonth) {
      if (currentMonth !== null) {
        groups.push({
          month: currentMonth,
          width: `${currentWidth * 40}px`
        })
      }
      currentMonth = monthKey
      currentWidth = 1
    } else {
      currentWidth++
    }
  })

  if (currentMonth !== null) {
    groups.push({
      month: currentMonth,
      width: `${currentWidth * 40}px`
    })
  }

  return groups
})

// 获取订单状态
const getOrderStatus = (order: TicketLedger) => {
  return order.ordersState === 2 ? 'completed' :
         order.ordersState === 1 ? 'processing' : 'created'
}

// 计算进度条样式
const getProgressBarStyle = (order: TicketLedger) => {
  if (!order.stateTime || !order.endTime) return { display: 'none' }

  const startDate = new Date(order.stateTime)
  const endDate = new Date(order.endTime)

  // 找到日期在dateRange中的索引
  const startIndex = dateRange.value.findIndex(d =>
    d.fullDate.getFullYear() === startDate.getFullYear() &&
    d.fullDate.getMonth() === startDate.getMonth() &&
    d.fullDate.getDate() === startDate.getDate()
  )
  const endIndex = dateRange.value.findIndex(d =>
    d.fullDate.getFullYear() === endDate.getFullYear() &&
    d.fullDate.getMonth() === endDate.getMonth() &&
    d.fullDate.getDate() === endDate.getDate()
  )

  if (startIndex === -1 || endIndex === -1) return { display: 'none' }

  // 计算宽度
  const cellWidth = 40
  let width = (endIndex - startIndex + 1) * cellWidth
  const minWidth = 120 // 设置最小宽度，避免太窄
  if (width < minWidth) width = minWidth

  // 根据订单状态设置颜色
  let backgroundColor = '#909399' // 默认灰色（创建状态）
  if (order.ordersState === 2) {
    backgroundColor = '#67c23a' // 绿色（完成状态）
  } else if (order.ordersState === 1) {
    backgroundColor = '#409eff' // 蓝色（进行中状态）
  }

  return {
    left: `${startIndex * cellWidth}px`,
    width: `${width}px`,
    background: backgroundColor,
    height: '32px',
    marginTop: '6px',
    opacity: '0.85',
    borderRadius: '4px',
    padding: '0 8px',
    display: 'flex',
    alignItems: 'center',
    position: 'absolute' as const,
    zIndex: '1'
  }
}

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null
  return function (this: any, ...args: any[]) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay) as unknown as number
  }
}

// 处理内容滚动
const handleContentScroll = debounce((e: Event) => {
  const container = e.target as HTMLElement
  const maxScroll = container.scrollWidth - container.clientWidth
  if (maxScroll <= 0) return

  scrollPosition.value = Math.round((container.scrollLeft / maxScroll) * 100)

  // 同步头部滚动
  if (timelineHeaderRef.value) {
    timelineHeaderRef.value.scrollLeft = container.scrollLeft
  }
}, 16)

// 处理滑块滚动
const handleScroll = debounce((value: number) => {
  if (!ganttContentRef.value) return

  const container = ganttContentRef.value
  const maxScroll = container.scrollWidth - container.clientWidth
  const scrollLeft = (maxScroll * value) / 100

  container.scrollTo({
    left: scrollLeft,
    behavior: 'smooth'
  })
}, 16)

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 计算进度
const getProgress = (order: any) => {
  return Math.round((order.completedQuantity / order.planQuantity) * 100)
}

// 显示提示
const showTooltip = (order: any) => {
  hoveredOrder.value = order.id
}

// 隐藏提示
const hideTooltip = () => {
  hoveredOrder.value = null
}

// 判断是否悬停
const isHovered = (order: any) => {
  return hoveredOrder.value === order.id
}

const syncHeaderScroll = () => {
  if (ganttContentRef.value && timelineHeaderRef.value) {
    timelineHeaderRef.value.scrollLeft = ganttContentRef.value.scrollLeft
  }
}

// 初始化
onMounted(async () => {
  await nextTick()
  if (ganttContentRef.value && ganttChartRef.value) {
    // 初始化滚动位置
    ganttContentRef.value.scrollLeft = 0
    scrollPosition.value = 0
  }
  if (ganttContentRef.value) {
    ganttContentRef.value.addEventListener('scroll', syncHeaderScroll)
  }
})
</script>

<style scoped>
.gantt-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 16px;
  gap: 16px;
}

.search-bar {
  display: flex;
  gap: 12px;
  align-items: center;
}

.add-btn {
  background-color: #00925d;
  border-color: #00925d;
}

.add-btn:hover {
  background-color: #00b377;
  border-color: #00b377;
}

.search-input {
  width: 240px;
}

.search-select {
  width: 180px;
}

.input-label {
  color: #606266;
  margin-right: 8px;
}

.gantt-wrapper {
  flex: 1;
  display: flex;
  border: 1px solid #dcdfe6;
  min-height: 300px;
  background-color: #fff;
  overflow: hidden;
}

.gantt-chart {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.timeline-header-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
  background: #f5f7fa;
}

.timeline-header {
  min-width: 1000px;
  /* 实际会被动态覆盖为dateRange.length*40px */
  white-space: nowrap;
}

.month-row {
  display: flex;
  border-bottom: 1px solid #dcdfe6;
  height: 36px;
}

.month-cell {
  padding: 8px 16px;
  font-size: 14px;
  color: #303133;
  border-right: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 36px;
  background-color: #f5f7fa;
}

.date-row {
  display: flex;
  height: 48px;
}

.date-cell {
  width: 40px;
  text-align: center;
  padding: 6px 0;
  flex-shrink: 0;
  border-right: 1px solid #dcdfe6;
  background-color: #fff;
}

.date-cell.weekend {
  background-color: #f5f7fa;
}

.date-number {
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.weekday {
  font-size: 12px;
  color: #909399;
}

.gantt-content {
  flex: 1;
  overflow: auto;
  position: relative;
}

.tasks-container {
  position: relative;
}

.gantt-row.align {
  height: 88px; /* 设置为标题行+数据行的总高度 */
  position: relative;
  border-bottom: 1px solid #ebeef5;
}

.product-group-title.align {
  height: 44px;
  font-weight: bold;
  font-size: 15px;
  background: #f0f2f5;
  padding: 0 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
}

.order-info {
  height: 44px;
  padding: 8px 16px;
  background: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.progress-bar.align {
  position: absolute;
  z-index: 1;
  height: 32px;
  margin-top: 48px; /* 调整垂直位置到数据行 */
  border-radius: 4px;
  transition: all 0.3s;
  cursor: pointer;
  min-width: 120px;
  padding: 0 8px;
  display: flex;
  align-items: center;
}

.progress-bar.align[data-status='completed'] {
  background: #67c23a;
}

.progress-bar.align[data-status='created'] {
  background: #909399;
}

.progress-bar.align[data-status='processing'] {
  background: #409eff;
}

.progress-bar.align:hover {
  height: 28px;
  margin-top: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.control-bar.custom-bar {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: transparent;
  border: none;
  box-shadow: none;
  margin-top: 24px;
  margin-bottom: 24px;
}

.bar-inner {
  display: flex;
  align-items: center;
  background: #f5f7fa;
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.06);
  padding: 10px 24px;
  gap: 12px;
  min-width: 320px;
}

.bar-inner .el-button,
.bar-inner .el-button-group .el-button {
  margin: 0 4px;
}

.bar-inner .el-slider {
  margin: 0 12px;
}

.product-info.align-mode {
  width: 320px;
  border-right: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  overflow-y: hidden;
}

.product-group-title.align {
  font-weight: bold;
  font-size: 15px;
  background: #f0f2f5;
  padding: 0 16px;
  border-bottom: 1px solid #e4e7ed;
  height: 44px;
  display: flex;
  align-items: center;
}

.product-item.align {
  padding: 8px 16px;
  height: 50px;
}

.order-id {
  display: block;
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.order-stats {
  display: block;
  font-size: 12px;
  color: #606266;
}

.tasks-container.align-mode {
  position: relative;
}
</style>